package com.dynamic.data.source.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.dynamic.data.source.config.DataSourceAdmin;
import com.dynamic.data.source.config.DynamicDataSource;
import com.dynamic.data.source.domain.Tenant;
import com.dynamic.data.source.mapper.UserMapper;
import com.dynamic.data.source.service.InitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * 开发公司：联信
 * 版权：联信
 * <p>
 * Annotation
 *
 * @author 刘志强
 * @created Create Time: 2021/1/26
 */
@Service
@Slf4j
public class InitServiceImpl implements InitService {

    private final UserMapper userMapper;
    private final Properties poolProperties;
    private final DataSource dynamicDataSource;

    public InitServiceImpl(UserMapper userMapper,
                           @Qualifier("dynamicDataSource") DataSource dynamicDataSource,
                           @Qualifier("poolProperties") Properties poolProperties) {
        this.userMapper = userMapper;
        this.dynamicDataSource = dynamicDataSource;
        this.poolProperties = poolProperties;
    }

    @Override
    public void initDataSource() {
        List<Tenant> list = userMapper.getTenantAll();
        list.forEach(tenant -> {
            // 创建数据源
            DruidDataSource dataSource = DataSourceBuilder.create()
                    // 数据库 连接池类型 如果不设置类型默认类型为 com.zaxxer.hikari.HikariDataSource
                    .type(DruidDataSource.class)
                    // 驱动
                    .driverClassName("com.mysql.cj.jdbc.Driver")
                    // 链接
                    .url(tenant.getTenantDatabaseUrl())
                    // 账号
                    .username(tenant.getTenantDatabaseName())
                    // 密码
                    .password(tenant.getTenantDatabasePassword())
                    .build();

            // 加载连接池配置信息
            dataSource.configFromPropety(poolProperties);
            try {
                log.info("租户数据源初始化{}",tenant.toString());
                dataSource.init();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            DataSourceAdmin.dataSourceMap.put(String.valueOf(tenant.getId()),dataSource);
        });
        // 初始化数据源
        DynamicDataSource dataSource = (DynamicDataSource) dynamicDataSource;
        dataSource.setDataSources(DataSourceAdmin.dataSourceMap);
        dataSource.afterPropertiesSet();
    }
}
